import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { App } from 'vue'
import { useUserStore } from '@/features/store/store'
import {
  useTabStore,
  useRouterHistoryStore,
  setTabStoreRouter,
} from '@/features/store/tabStore'
import { setComponentStoreRouter } from '@/features/store/componentStore'
import { setRequestRouter } from '@/request/request'
import { throttle, debounce } from '@/utils/func'

const Login = () => import('@/views/Login/login.vue')
const Home = () => import('@/views/Home/home.vue')
const User = () => import('@/views/User/user.vue')

const AuthorityControl = () =>
  import('@/views/AuthorityControl/authorityControl.vue')
const UserManage = () =>
  import('@/views/AuthorityControl/UserManage/userManage.vue')
const RoleManage = () =>
  import('@/views/AuthorityControl/RoleManage/roleManage.vue')
const PermissionManage = () =>
  import('@/views/AuthorityControl/PermissionManage/permissionManage.vue')
const PageManage = () =>
  import('@/views/AuthorityControl/PageManage/pageManage.vue')
const SystemManage = () =>
  import('@/views/AuthorityControl/SystemManage/systemManage.vue')
const SortManage = () =>
  import('@/views/AuthorityControl/SortManage/sortManage.vue')
const LogManage = () =>
  import('@/views/AuthorityControl/LogManage/logManage.vue')

const AccessIpManage = () => import('@/views/AccessIpManage/accessIpManage.vue')
const IpControlList = () =>
  import('@/views/AccessIpManage/IpControlList/ipControlList.vue')
const RejectionRecord = () =>
  import('@/views/AccessIpManage/RejectionRecord/rejectionRecord.vue')

const AiService = () => import('@/views/AiService/aiService.vue')
const AiServiceRecord = () =>
  import('@/views/AiService/AiServiceRecord/aiServiceRecord.vue')

const SubApplication = () => import('@/views/SubApplication/subApplication.vue')

// 导入的路由页面
const routeMap: { [key: string]: any } = {
  Home: Home,
  User: User,

  AuthorityControl: AuthorityControl,
  UserManage: UserManage,
  RoleManage: RoleManage,
  PermissionManage: PermissionManage,
  PageManage: PageManage,
  SystemManage: SystemManage,
  SortManage: SortManage,
  LogManage: LogManage,
  Application: SubApplication,

  AccessIpManage: AccessIpManage,
  IpControlList: IpControlList,
  RejectionRecord: RejectionRecord,

  AiService: AiService,
  AiServiceRecord: AiServiceRecord,

  SubApplication: SubApplication,
}

// 本地无权限页面
const LocalNoRightRoutes: RouteRecordRaw[] = [
  { path: '/', redirect: '/home' },
  { path: '/login', name: 'Login', component: Login },
]

// @ts-ignore
// 本地有权限页面
const LocalRightRoutes: RouteRecordRaw[] = [
  { path: '/home', name: 'Home', component: Home },
  { path: '/user', name: 'User', component: User },
  {
    path: '/authorityControl',
    name: 'AuthorityControl',
    component: AuthorityControl,
  },
  { path: '/userManage', name: 'UserManage', component: UserManage },
  { path: '/roleManage', name: 'RoleManage', component: RoleManage },
  {
    path: '/permissionManage',
    name: 'PermissionManage',
    component: PermissionManage,
  },
  { path: '/pageManage', name: 'PageManage', component: PageManage },
  { path: '/systemManage', name: 'SystemManage', component: SystemManage },
  { path: '/sortManage', name: 'SortManage', component: SortManage },
  { path: '/logManage', name: 'LogManage', component: LogManage },

  {
    path: '/accessIpManage',
    name: 'AccessIpManage',
    component: AccessIpManage,
  },
  {
    path: '/ipControlManage',
    name: 'IpControlList',
    component: IpControlList,
  },
  {
    path: '/rejectionRecordManage',
    name: 'RejectionRecord',
    component: RejectionRecord,
  },

  { path: '/aiService', name: 'AiService', component: AiService },
  {
    path: '/aiServiceRecord',
    name: 'AiServiceRecord',
    component: AiServiceRecord,
  },

  {
    path: '/subApplication',
    name: 'Application',
    component: SubApplication,
  },
  {
    path: '/subApplication/:catchAll(.*)*',
    name: 'SubApplication',
    component: SubApplication,
  },
]

// 404页面
const NotFound = () => import('@/views/NotFound/notFound.vue')
const notFound: RouteRecordRaw = {
  path: '/:catchAll(.*)*',
  name: '404',
  component: NotFound,
}

//
//
// 默认路由页面
let routes: RouteRecordRaw[] = LocalNoRightRoutes

const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 封装路由初始化方法
export const initRouter = (app: App<Element>) => {
  app.use(router)
}
export const getRouterInstance = () => router
// 传递路由给axios实例使用
setRequestRouter(router)
// 传递给componentStore使用
setComponentStoreRouter(router)
// 传递给tabStore使用
setTabStoreRouter(router)

//
//
// @ts-ignore
const extractRoutes = (routeList: RouteItf[]): RouteRecordRaw[] => {
  if (routeList?.length === 0) return []
  return formattingDataStructure(routeList)

  function formattingDataStructure(arr: RouteItf[], parentId = '') {
    const result = []
    if (arr == null || arr.length === 0) return []

    for (const item of arr) {
      if (item.parentId == parentId) {
        const children = formattingDataStructure(arr, item.id)
        if (children.length > 0) {
          result.push({
            path: item.path,
            name: item.name,
            component: routeMap[item.component],
            children: children,
          })
        } else {
          result.push({
            path: item.path,
            name: item.name,
            component: routeMap[item.component],
          })
        }
      }
    }
    return result
  }
}

//
// 路由是否进行重定向，第一次加载时进行
let routerRedirect = true
let rightRoutes: RouteRecordRaw[]
//
// @ts-ignore
// 路由前置守卫
router.beforeEach(async (to, from, next) => {
  // @ts-ignore
  const { loginStatus, remoteRoutes, getUserInfo, resetData } = useUserStore()
  rightRoutes = extractRoutes(remoteRoutes)
  // rightRoutes = LocalRightRoutes
  // console.log(rightRoutes)

  if (!loginStatus && to.path == '/login') return next()
  if (!window.localStorage.getItem('token') || to.path == '/loginRedirect') {
    // 退出时清除路由
    for (const key in rightRoutes) {
      if (router.hasRoute(rightRoutes[key].name))
        router.removeRoute(rightRoutes[key].name)
    }
    resetData()
    return next('/login')
  }

  // 当第一次加载路由时进行重定向，方便开发时使用
  if (routerRedirect && rightRoutes.length !== 0) {
    routerRedirect = false
    for (const key in rightRoutes) router.addRoute(rightRoutes[key])
    return next(to)
  }

  if (loginStatus) {
    for (const key in rightRoutes) router.addRoute(rightRoutes[key])
    router.addRoute(notFound)

    // 第一次进入系统时进行重定向
    if (to.path == '/homeRedirect') return next('/home')
    return next()
  } else {
    if (await getUserInfo()) return next(to)

    for (const key in rightRoutes) {
      if (router.hasRoute(rightRoutes[key].name))
        router.removeRoute(rightRoutes[key].name)
    }
    next('/login')
  }
})

// 封装的节流函数
const throttleFunc = throttle((toPath: string) => {
  const l = useTabStore().tabList.filter((item) => toPath.includes(item.path))
  if (l !== null && l.length > 0) useTabStore().setCurrentTabId(l[0].id)
  else useTabStore().setCurrentTabId('')

  const temp = useUserStore().remoteRoutes.filter(
    (item) => item.path === toPath && item.isNavigation === 0
  )
  if (temp.length > 0) {
    useTabStore().setAppHistoryPath(temp[0].path, temp[0].description)
  }
}, 200)

// 封装防抖函数
const debounceFunc = debounce(
  (path: string) => useRouterHistoryStore().setPathHistory(path),
  200
)

// @ts-ignore
// 注册后置路由守卫
router.afterEach((to, from) => {
  // 调用节流函数并传递参数
  throttleFunc(to.fullPath)

  // 可以在这里执行页面跟踪、权限验证等操作
  debounceFunc(to.fullPath) // 记录一下路由跳转路径
})
